﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace BaseHelper.Base
{
    public class IniHelper
    {

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filepath);

        public static string Path;

        public static void Write(string path, string section, string key, string value)
        {
            if (!File.Exists(path))
                File.Create(path);
            WritePrivateProfileString(section, key, value, path);
        }
        public static string Read(string path, string section, string key)
        {
            StringBuilder temp = new StringBuilder(255);
            GetPrivateProfileString(section, key, "", temp, 255, path);
            return temp.ToString();
        }

        public static string Read(string section, string key, ref string name)
        {
            name = Read(section, key);
            return name;
        }
        public static int ReadInt(string section, string key, ref int name)
        {
            name = ReadInt(section, key);
            return name;
        }

        public static string Read( string section, string key,string eqvalue="",string def="")
        {
            StringBuilder temp = new StringBuilder(1000);
            GetPrivateProfileString(section, key, "", temp, 1000, Path);
            if (temp.ToString() == eqvalue)
                return def;
            return temp.ToString();
        }
        public static int ReadInt(string section, string key,int eqvalue=-1,int def=0)
        {
            string tmp = Read(section, key);
            tmp = tmp == "" ? "0" : tmp;
            try
            {

                int ret = Convert.ToInt32(tmp);
                if (eqvalue >= 0)
                {
                    if (eqvalue == ret)
                        return def;
                }
                return ret;
            }
            catch
            {
                return def;
            }
        }
        public static bool ReadBool(string section, string key, bool def = false)
        {
            string tmp = Read(section, key);
            if (tmp == "")
                return def;
            else
                return tmp.ToUpper().Equals("TRUE");
        }
        public static void Write(string section, string key, object value)
        {
            if (!File.Exists(Path))
                File.Create(Path);

            WritePrivateProfileString(section, key, value.ToString(), Path);
        }
    }
}
